<?php

class DictBatteryController extends RController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
    public $defaultAction = 'admin';
	public $layout='//layouts/lay_column2';
    public $menu=array();
    public $moduleName="电池规格";	//姝ゅ淇敼鏈ā鍧楀悕绉�
    
    public function init()
	{
    	$leftmenu = 'jichu';	//姝ゅ淇敼妯″潡鎵�睘鑿滃崟
		$this->menu = Yii::app()->params[$leftmenu];
	}

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'rights', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('@'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update', 'recompute', 'download', 'downloadPdf', 'upload', 'clean'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	
	public function actionRecompute($id)
	{
		$rs = array();
		$sql = 'select count(*)*sum(t.inter_n*t.inter_n) -sum(t.inter_n)*sum(t.inter_n)
				from tbl_compute t where t.bttypekey_v = '.$id;
		$command = Yii::app()->db->createCommand($sql);
		$nd = $command->queryScalar();	
			
		//echo $nd;
		
		$sql = 'select sum(t.forcastvolume_n)*sum(t.inter_n*t.inter_n)- sum( t.inter_n*t.forcastvolume_n)*sum(t.inter_n)
				from tbl_compute t where t.bttypekey_v = '.$id;
		$command = Yii::app()->db->createCommand($sql);
		$nd1 = $command->queryScalar();
		//echo $nd1;

		$sql = 'select count(*)*sum( t.inter_n*t.forcastvolume_n)-sum(t.inter_n)*sum(t.forcastvolume_n)
				from tbl_compute t where t.bttypekey_v = '.$id;
		$command = Yii::app()->db->createCommand($sql);
		$nd2 = $command->queryScalar();
		//echo $nd2;
				
		if($nd != 0){
			$b0 = $nd1 / $nd;
			$b1 = $nd2 / $nd;
		}else{
			$b0 = 0;
			$b1 = 0;
		}
		
		$b0 = number_format($b0, 3);
		$b1 = number_format($b1, 3);
		
		$rs = array(
			'no' => 0,
			'data' => array(
				'b0' => $b0,
				'b1' => $b1
			),
			'error' => ''
		);
		
		Compute::model()->deleteAll('BTTYPEKEY_V=:bttypekey', array(':bttypekey'=>-1));
		
		echo json_encode($rs);
	}

	public function actionClean($id)
	{
		$rs = array(
				'no' => 1,
				'data' => array(),
				'error' => ''
		);
		if(Compute::model()->deleteAll('BTTYPEKEY_V=:bttypekey', array(':bttypekey'=>$id)) === 0){
			$rs = array(
					'no' => 0,
					'data' => array(),
					'error' => ''
			);
		}
		echo json_encode($rs);
	}
	
	public function actionDownload()
	{
//		echo 'Enter download actoin';
		EDownloadHelper::download(Yii::getPathOfAlias('webroot').DIRECTORY_SEPARATOR.'excel/battery.xls');
	}
	
	public function actionDownloadPdf()
	{
		//		echo 'Enter download actoin';
		EDownloadHelper::download(Yii::getPathOfAlias('webroot').DIRECTORY_SEPARATOR.'excel/help.pdf');
	}
	
	
	public function actionUpload($id)
	{
		$model=new DictBattery;
		$model->unsetAttributes();  // clear any default values

		$rs = array(
				'no' => 1,
				'data' => array(),
				'error' => ''
		);
		
		$success = 0;
		
		if(isset($_POST['DictBattery'])){
			$uploadTempPath='C:/';
			$file1=CUploadedFile::getInstance($model,'image');
			if($file1)
			{
//				echo 'get file';
				$filename=$file1->getName();
//				echo $filename;
				$filename1 = $uploadTempPath.$filename;
				if(file_exists($filename1))
					$filename1 = $uploadTempPath.uniqid("uploadfile");
				$file1->saveAs($filename1);

				Yii::import('application.modules.vendors.PHPExcel',true);
				
				$objReader = new PHPExcel_Reader_Excel5;	
				if (!file_exists($filename1)) {
					exit("not found file.\n");
				}							
				$objPHPExcel = $objReader->load($filename1);
				$objWorksheet = $objPHPExcel->getActiveSheet();
				$highestRow = $objWorksheet->getHighestRow(); // e.g. 10
				$highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'
				$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5
//				echo '<table>' . "\n";

				for ($row = 2; $row <= $highestRow; ++$row) {
//					echo '<tr>' . "\n";
					//			for ($col = 1; $col <= $highestColumnIndex; ++$col) {
					//				echo '<td>' . $objWorksheet->getCellByColumnAndRow($col, $row)->getValue() . '</td>' . "\n";
					$model=new Compute;
					//$model->RECORD_ID = $objWorksheet->getCellByColumnAndRow(0, $row)->getValue();
					$model->FORCASTVOLUME_N = $objWorksheet->getCellByColumnAndRow(1, $row)->getValue();
					$model->VOL_N = $objWorksheet->getCellByColumnAndRow(2, $row)->getValue();
					$model->INTER_N = $objWorksheet->getCellByColumnAndRow(3, $row)->getValue();
					$model->BTKEY_V = '0';
					$model->BTTYPEKEY_V = $id;
					
					if(empty($model->FORCASTVOLUME_N))
						break;
					
					if($model->save()){
						$success = 1;
					}
					else{
						$success = 0;
					}
					
					if($id == -1){
						$model=new Compute;
						$sql = 'select max(RECORD_ID) from dict_battery';
						$command = Yii::app()->db->createCommand($sql);
						$max_id = $command->queryScalar();
						 
						$model->FORCASTVOLUME_N = $objWorksheet->getCellByColumnAndRow(1, $row)->getValue();
						$model->VOL_N = $objWorksheet->getCellByColumnAndRow(2, $row)->getValue();
						$model->INTER_N = $objWorksheet->getCellByColumnAndRow(3, $row)->getValue();
						$model->BTKEY_V = '0';
						$model->BTTYPEKEY_V = ($max_id + 1);
						
						if($model->save()){
							$success = 1;
						}
						else{
							$success = 0;
						}
					}
				
//					echo '<td>' .'鐢靛帇'. $model->VOL_N . '</td>' . "\n";
//					echo '<td>' .'鐢甸樆'. $model->INTER_N . '</td>' . "\n";
//					echo '<td>' . '鐢靛'. $model->FORCASTVOLUME_N . '</td>' . "\n";		
									
					//			}
//					echo '</tr>' . "\n";
				}
//				echo '</table>' . "\n";				
				//rm file
				unlink ($filename1);
				$error = '数据导入成功' ;
				//throw new CHttpException(200, $error);
			}
		}

		$rs = array(
				'no' => 1,
				'data' => $success,
				'error' => ''
		);
		
		//echo json_encode($rs);
		
		$this->renderPartial('upload',array(
				'model'=>$model,
				'success' => $success,
		));
/*		
		if (!file_exists("examples.xls")) {
			exit("not found examples.xls.\n");
		}
		$model=new BtRunData;
		Yii::import('application.modules.vendors.PHPExcel',true);
		$objReader = new PHPExcel_Reader_Excel5;

		$objPHPExcel = $objReader->load('examples.xls');
		$objWorksheet = $objPHPExcel->getActiveSheet();
		$highestRow = $objWorksheet->getHighestRow(); // e.g. 10
		$highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'
		$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5
		echo '<table>' . "\n";
		for ($row = 2; $row <= $highestRow; ++$row) {
			echo '<tr>' . "\n";
//			for ($col = 1; $col <= $highestColumnIndex; ++$col) {
//				echo '<td>' . $objWorksheet->getCellByColumnAndRow($col, $row)->getValue() . '</td>' . "\n";
				$model=new BtRunData;
				$model->FORCASTVOLUME_N = $objWorksheet->getCellByColumnAndRow(1, $row)->getValue();
				$model->VOL_N = $objWorksheet->getCellByColumnAndRow(2, $row)->getValue();
				$model->INTER_N = $objWorksheet->getCellByColumnAndRow(3, $row)->getValue();
				$model->BTKEY_V = '0';
				$model->BTTYPEKEY_V = 9;
				
				echo '<td>' .'鐢靛帇'. $model->VOL_N . '</td>' . "\n";
				echo '<td>' .'鐢甸樆'. $model->INTER_N . '</td>' . "\n";
				echo '<td>' . '鐢靛'. $model->FORCASTVOLUME_N . '</td>' . "\n";

//				if($model->validate())
//					echo 'validatae OK';
//				else 
//					echo 'validate false';
				
//				var_dump($model->getErrors());
				
				if($model->save())
					echo 'success';
				else 
					echo 'failed';
//			}
			echo '</tr>' . "\n";
		}
		echo '</table>' . "\n";
*/
	}
	
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new DictBattery;
		$manumodel = new DictManufacturer;
		$btsortmodel = new DictBatterySort;
		$btrun = new BtRundata;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['DictBattery']))
		{
			$model->attributes=$_POST['DictBattery'];
			
			$model->BATTERYSORT_V = $_POST['DictBatterySort']['RECORD_ID'];
			$model->MANCODE_V = $_POST['DictManufacturer']['RECORD_ID'];
			$model->CREATE_DATE = '2012-12-21';
//			$model->ISINNER =  $_POST['DictBattery']['ISINNER'];
			
			if($model->save())
				$this->redirect(array('view','id'=>$model->RECORD_ID));
		}	

		$manufacturer = DictManufacturer::model()->findAll();
		$batterysort = DictBatterySort::model()->findAll();
		
		$this->render('create',array(
			'model'=>$model,
			'manumodel' => $manumodel,
			'manufacturer'=>$manufacturer,
			'btsortmodel' => $btsortmodel,
			'batterysort'=>$batterysort,
			'btrun' => $btrun,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$manumodel = new DictManufacturer;
		$btsortmodel = new DictBatterySort;
		$btrun = new BtRundata;
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['DictBattery']))
		{
			$model->attributes=$_POST['DictBattery'];
//			$model->BATTERYSORT_V = $_POST['DictBatterySort']['RECORD_ID'];
////			$model->MANCODE_V = $_POST['DictManufacturer']['RECORD_ID'];
//			$model->ISINNER =  $_POST['DictBattery']['ISINNER'];
			$model->BATTERYSORT_V = $_POST['DictBatterySort']['RECORD_ID'];
			$model->MANCODE_V = $_POST['DictManufacturer']['RECORD_ID'];
			$model->CREATE_DATE = '2012-12-21';
				
			if($model->save())
				$this->redirect(array('view','id'=>$model->RECORD_ID));
		}

		$manufacturer = DictManufacturer::model()->findAll();
		$batterysort = DictBatterySort::model()->findAll();
		
		$this->render('update',array(
			'model'=>$model,
			'manumodel' => $manumodel,
			'manufacturer'=>$manufacturer,
			'btsortmodel' => $btsortmodel,
			'batterysort'=>$batterysort,
			'btrun' => $btrun,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model = $this->loadModel($id);
			$condition = 'BATTERYTYPE_V = :manname';
			$params = array(':manname' => $model->RECORD_ID);
			$exists = BtBatterys::model()->exists($condition, $params);
			
			if($exists){
				$error = '请先删除对应电池规格的电池组' ;
				throw new CHttpException(404, $error);
			}			
			
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('DictBattery');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new DictBattery('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['DictBattery']))
			$model->attributes=$_GET['DictBattery'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=DictBattery::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='dict-battery-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
